import React, { useState, useEffect, useRef } from 'react';
import { Layout, Typography, Card, List, Divider, Button, Modal, Upload, message, Input, InputRef, Tabs, Dropdown } from 'antd';
import {
  FilePdfOutlined,
  PlusOutlined,
  SearchOutlined,
  StarOutlined,
  StarFilled,
  PushpinOutlined,
  PushpinFilled,
  EllipsisOutlined,
  DownloadOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FileTextOutlined,
  FileImageOutlined,
  FileUnknownOutlined,
  CaretUpOutlined,
  CaretDownOutlined,
  SortAscendingOutlined,
  FilterOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { getFormInitialValues, saveFormInitialValues } from '../../components/utils/formStorage';
import notificationService from '../../services/notificationService';
import errorHandlerService from '../../services/errorHandlerService';

const { Content } = Layout;
const { Title } = Typography;

interface Document {
  id: string;
  name: string;
  size: string;
  date: string;
  isPinned?: boolean;
  isFavorite?: boolean;
}

interface DocumentManagerProps {
  title: string;
  category: string;
  addButtonText: string;
  emptyText: string;
  uploadHint: string;
  localStorageKey: string;
  type: string; // 添加类型参数
}

const DocumentManager: React.FC<DocumentManagerProps> = ({ 
  title, 
  category, 
  addButtonText, 
  emptyText, 
  uploadHint,
  localStorageKey,
  type
}) => {
  // 文档列表状态
  const [documents, setDocuments] = useState<Document[]>([]);
  // 原始文档列表，用于搜索恢复
  const [originalDocuments, setOriginalDocuments] = useState<Document[]>([]);
  // 添加文档对话框状态
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  // 上传状态
  const [fileList, setFileList] = useState<Array<any>>([]);
  // 搜索关键词
  const [searchKeyword, setSearchKeyword] = useState('');
  // 搜索框引用
  const searchInput = useRef<InputRef>(null);
  // 选中的文档ID列表
  const [selectedDocuments, setSelectedDocuments] = useState<string[]>([]);
  // 是否显示收藏标签
  const [showFavoritesOnly, setShowFavoritesOnly] = useState(false);
  // 排序相关状态
  const [sortBy, setSortBy] = useState<'name' | 'date' | 'size'>('date');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  // 文件类型筛选状态
  const [selectedFileType, setSelectedFileType] = useState<string>('all');

  // 初始化加载文档列表
  useEffect(() => {
    loadDocuments();
  }, []);

  // 加载文档列表
  const loadDocuments = async () => {
    try {
      const response = await (window as any).electron.ipc.invoke('load-regulations', { type });
      if (response && response.success) {
        // 从本地存储加载置顶和收藏状态
  const savedStates = getFormInitialValues(localStorageKey) || {};
        const documentsWithStates = response.data.map((doc: any) => ({
          ...doc,
          isPinned: savedStates[doc.id]?.isPinned || false,
          isFavorite: savedStates[doc.id]?.isFavorite || false
        }));
        
        // 按置顶状态排序
        documentsWithStates.sort((a: Document, b: Document) => {
          if (a.isPinned && !b.isPinned) return -1;
          if (!a.isPinned && b.isPinned) return 1;
          return 0;
        });
        
        setDocuments(documentsWithStates);
        setOriginalDocuments(documentsWithStates); // 保存原始列表用于搜索
      }
      } catch (error) {
      console.error(`加载${category}列表失败:`, error);
      notificationService.error(`加载${category}列表失败`);
    }
  };

  // 保存文档状态到本地存储
  const saveDocumentState = (documentId: string, state: {isPinned?: boolean, isFavorite?: boolean}) => {
    const savedStates = getFormInitialValues(localStorageKey) || {};
    savedStates[documentId] = { ...savedStates[documentId], ...state };
    saveFormInitialValues(localStorageKey, savedStates);
  };

  // 切换置顶状态
  const togglePin = (documentId: string, isPinned: boolean) => {
    setDocuments(prevDocuments => {
      const updatedDocuments = prevDocuments.map(doc => 
        doc.id === documentId ? { ...doc, isPinned: !isPinned } : doc
      );
      
      // 重新排序，置顶项排在前面
      updatedDocuments.sort((a: Document, b: Document) => {
        if (a.isPinned && !b.isPinned) return -1;
        if (!a.isPinned && b.isPinned) return 1;
        return 0;
      });
      
      return updatedDocuments;
    });
    
    setOriginalDocuments(prevDocuments => 
      prevDocuments.map(doc => 
        doc.id === documentId ? { ...doc, isPinned: !isPinned } : doc
      )
    );
    
  saveDocumentState(documentId, { isPinned: !isPinned });
  notificationService.success(isPinned ? '已取消置顶' : '已置顶');
  };

  // 切换收藏状态
  const toggleFavorite = (documentId: string, isFavorite: boolean) => {
    setDocuments(prevDocuments => 
      prevDocuments.map(doc => 
        doc.id === documentId ? { ...doc, isFavorite: !isFavorite } : doc
      )
    );
    
    setOriginalDocuments(prevDocuments => 
      prevDocuments.map(doc => 
        doc.id === documentId ? { ...doc, isFavorite: !isFavorite } : doc
      )
    );
    
  saveDocumentState(documentId, { isFavorite: !isFavorite });
  notificationService.success(isFavorite ? '已取消收藏' : '已收藏');
  };

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedDocuments.length === documents.length) {
      setSelectedDocuments([]);
    } else {
      setSelectedDocuments(documents.map(doc => doc.id));
    }
  };

  // 切换单个选择
  const toggleSelect = (documentId: string) => {
    setSelectedDocuments(prevSelected => 
      prevSelected.includes(documentId) 
        ? prevSelected.filter(id => id !== documentId) 
        : [...prevSelected, documentId]
    );
  };

  // 批量置顶
  const batchPin = () => {
    if (selectedDocuments.length === 0) {
  notificationService.warning(`请先选择要置顶的${category}`);
      return;
    }
    
    setDocuments(prevDocuments => {
      const updatedDocuments = prevDocuments.map(doc => 
        selectedDocuments.includes(doc.id) ? { ...doc, isPinned: true } : doc
      );
      
      // 重新排序
      updatedDocuments.sort((a: Document, b: Document) => {
        if (a.isPinned && !b.isPinned) return -1;
        if (!a.isPinned && b.isPinned) return 1;
        return 0;
      });
      
      return updatedDocuments;
    });
    
    setOriginalDocuments(prevDocuments => 
      prevDocuments.map(doc => 
        selectedDocuments.includes(doc.id) ? { ...doc, isPinned: true } : doc
      )
    );
    
    // 保存状态
    selectedDocuments.forEach(id => {
      saveDocumentState(id, { isPinned: true });
    });
    
  notificationService.success(`已将 ${selectedDocuments.length} 个${category}置顶`);
    setSelectedDocuments([]);
  };

  // 批量收藏
  const batchFavorite = () => {
    if (selectedDocuments.length === 0) {
  notificationService.warning(`请先选择要收藏的${category}`);
      return;
    }
    
    setDocuments(prevDocuments => 
      prevDocuments.map(doc => 
        selectedDocuments.includes(doc.id) ? { ...doc, isFavorite: true } : doc
      )
    );
    
    setOriginalDocuments(prevDocuments => 
      prevDocuments.map(doc => 
        selectedDocuments.includes(doc.id) ? { ...doc, isFavorite: true } : doc
      )
    );
    
    // 保存状态
    selectedDocuments.forEach(id => {
      saveDocumentState(id, { isFavorite: true });
    });
    
  notificationService.success(`已收藏 ${selectedDocuments.length} 个${category}`);
    setSelectedDocuments([]);
  };
  
  // 批量删除
  const batchDelete = () => {
    if (selectedDocuments.length === 0) {
  notificationService.warning(`请先选择要删除的${category}`);
      return;
    }
    
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedDocuments.length} 个${category}文件吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return new Promise(async (resolve, reject) => {
          try {
            const deletePromises = documents
              .filter(doc => selectedDocuments.includes(doc.id))
              .map(doc => 
                (window as any).electron.ipc.invoke('delete-regulation', { type, fileName: doc.name })
              );
            
            await Promise.all(deletePromises);
            notificationService.success(`已删除 ${selectedDocuments.length} 个${category}文件`);
            loadDocuments(); // 重新加载文档列表
            setSelectedDocuments([]);
            resolve(true);
          } catch (error) {
            console.error(`批量删除${category}失败:`, error);
            notificationService.error(`批量删除${category}失败`);
            reject();
          }
        });
      }
    });
  };

  // 打开添加文档对话框
  const showAddModal = () => {
    setIsAddModalVisible(true);
  };

  // 关闭添加文档对话框
  const handleAddModalCancel = () => {
    setIsAddModalVisible(false);
    setFileList([]);
  };

  // 处理文件上传变化
  const handleUploadChange = ({ fileList }: any) => {
    setFileList(fileList);
  };

  // 处理添加文档
  const handleAddDocument = async () => {
    if (fileList.length === 0) {
  notificationService.warning('请先选择要上传的文件');
      return;
    }

    try {
      if (!(window as any).electron?.ipc?.invoke) {
        errorHandlerService.handleIpcError(new Error('添加文件功能不可用'), 'electron.ipc.invoke');
        return;
      }

      const uploadPromises = fileList
        .filter((file: any) => file.originFileObj)
        .map((file: any) => {
          return new Promise<void>((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = async (e) => {
              try {
                const fileData = e.target?.result as string;
                const response = await (window as any).electron.ipc.invoke('add-regulation', {
                  type,
                  fileName: file.originFileObj.name,
                  fileData: fileData.split(',')[1] // 去掉Base64前缀
                });

                if (response && response.success) {
                  resolve();
                } else {
                  reject(new Error(response?.error || `上传文件 ${file.originFileObj.name} 失败`));
                }
              } catch (error) {
                reject(error);
              }
            };
            reader.onerror = reject;
            reader.readAsDataURL(file.originFileObj);
          });
        });

      // 批量上传所有文件
      await Promise.all(uploadPromises);

      notificationService.success(`成功上传 ${fileList.length} 个${category}文件`);
      setIsAddModalVisible(false);
      setFileList([]);
      loadDocuments(); // 重新加载文档列表
    } catch (error: any) {
      errorHandlerService.handleFileError(
        error,
        '添加',
        `${category}添加失败`
      );
    }
  };

  // 打开文档文件
  const openDocument = async (fileName: string) => {
    try {
      if (!(window as any).electron?.ipc?.invoke) {
        errorHandlerService.handleIpcError(new Error('打开文件功能不可用'), 'electron.ipc.invoke');
        return;
      }

      const response = await (window as any).electron.ipc.invoke('open-regulation', { type, fileName });
      if (!response || !response.success) {
        errorHandlerService.handleFileError(
          new Error(response?.error || `打开${category}失败`),
          '打开'
        );
      }
    } catch (error: any) {
      errorHandlerService.handleFileError(
        error,
        '打开',
        `打开${category}失败`
      );
    }
  };

  // 删除文档
  const deleteDocument = async (fileName: string) => {
    console.log('删除按钮被点击，文件名:', fileName);
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除${category}文件 "${fileName}" 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        console.log('确认删除对话框 - 确定按钮被点击');
        try {
          if (!(window as any).electron?.ipc?.invoke) {
            errorHandlerService.handleIpcError(new Error('删除功能不可用'), 'electron.ipc.invoke');
            return;
          }

          const response = await (window as any).electron.ipc.invoke('delete-regulation', { type, fileName });
          if (response && response.success) {
            notificationService.success(`${category}删除成功`);
            loadDocuments(); // 重新加载文档列表
          } else {
            errorHandlerService.handleFileError(
              new Error(response?.error || `${category}删除失败`),
              '删除'
            );
          }
        } catch (error: any) {
          errorHandlerService.handleFileError(
            error,
            '删除',
            `${category}删除失败`
          );
        }
      }
    });
  };

  // 保存文档文件到本地
  const saveDocument = async (fileName: string) => {
    try {
      if (!(window as any).electron?.ipc?.invoke) {
        errorHandlerService.handleIpcError(new Error('保存文件功能不可用'), 'electron.ipc.invoke');
        return;
      }

      const response = await (window as any).electron.ipc.invoke('save-regulation', { type, fileName });
      if (response && response.success) {
        notificationService.success('文件保存成功');
      } else {
        if (response?.error !== '保存操作已取消') {
          errorHandlerService.handleFileError(
            new Error(response?.error || '保存文件失败'),
            '保存'
          );
        }
      }
    } catch (error: any) {
      errorHandlerService.handleFileError(
        error,
        '保存',
        `保存${category}失败`
      );
    }
  };

  // 搜索文档文件（可传入覆盖的收藏筛选标志和文件类型，解决状态更新的竞态问题）
  const handleSearch = (favoritesOverride?: boolean, fileTypeOverride?: string) => {
    console.log('搜索按钮被点击，搜索关键词:', searchKeyword, '收藏筛选:', favoritesOverride, '文件类型:', fileTypeOverride);
    const useFavorites = typeof favoritesOverride === 'boolean' ? favoritesOverride : showFavoritesOnly;
    const useFileType = typeof fileTypeOverride === 'string' ? fileTypeOverride : selectedFileType;

    let filtered = originalDocuments;

    if (useFavorites) {
      filtered = filtered.filter(doc => doc.isFavorite);
    }

    if (searchKeyword.trim()) {
      filtered = filtered.filter(doc => 
        doc.name.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }
    
    // 文件类型筛选
    if (useFileType !== 'all') {
      filtered = filtered.filter(doc => {
        const extension = doc.name.split('.').pop()?.toLowerCase() || '';
        switch (useFileType) {
          case 'pdf':
            return extension === 'pdf';
          case 'word':
            return ['doc', 'docx'].includes(extension);
          case 'excel':
            return ['xls', 'xlsx'].includes(extension);
          case 'text':
            return ['txt', 'md'].includes(extension);
          case 'image':
            return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension);
          case 'blueprint':
            return ['dwg', 'dxf', 'svg', 'ai', 'eps'].includes(extension);
          case 'other':
            // 其他类型 - 除了已经定义的PDF、Word、Excel、文本、图片和蓝图文件外的所有文件
            return !['pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt', 'md', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'dwg', 'dxf', 'svg', 'ai', 'eps'].includes(extension);
          default:
            return true;
        }
      });
    }

    // 排序功能：首先是置顶项排在前面，然后根据用户选择的排序方式排序
    filtered.sort((a: Document, b: Document) => {
      // 置顶项始终排在前面
      if (a.isPinned && !b.isPinned) return -1;
      if (!a.isPinned && b.isPinned) return 1;
      
      // 根据排序选项进行排序
      let comparison = 0;
      
      switch (sortBy) {
        case 'name':
          comparison = a.name.localeCompare(b.name);
          break;
        case 'date':
          // 假设date是字符串格式的日期，我们需要先将其转换为可比较的格式
          comparison = new Date(a.date).getTime() - new Date(b.date).getTime();
          break;
        case 'size':
          // 提取数字部分进行比较（移除单位如KB, MB等）
          const sizeA = parseFloat(a.size);
          const sizeB = parseFloat(b.size);
          comparison = sizeA - sizeB;
          break;
      }
      
      // 根据排序顺序调整结果
      return sortOrder === 'asc' ? comparison : -comparison;
    });

    setDocuments(filtered);
  };

  // 根据文件扩展名获取相应的图标
  const getFileIcon = (fileName: string) => {
    const extension = fileName.split('.').pop()?.toLowerCase() || '';
    
    // 确保图标大小一致性
    const iconStyle = { fontSize: '16px' };
    
    switch (extension) {
      case 'pdf':
        return <FilePdfOutlined style={{ ...iconStyle, color: 'var(--app-danger-color, #ff4d4f)' }} />;
      case 'doc':
      case 'docx':
        return <FileWordOutlined style={{ ...iconStyle, color: 'var(--app-primary-color, #1890ff)' }} />;
      case 'xls':
      case 'xlsx':
        return <FileExcelOutlined style={{ ...iconStyle, color: 'var(--app-success-color, #52c41a)' }} />;
      case 'txt':
      case 'md':
        return <FileTextOutlined style={{ ...iconStyle, color: 'var(--app-text-color, #000000)' }} />;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
      case 'bmp':
      case 'webp':
        return <FileImageOutlined style={{ ...iconStyle, color: 'var(--app-purple-color, #722ed1)' }} />;
      // 蓝图文件类型
      case 'dwg':
      case 'dxf':
      case 'svg':
      case 'ai':
      case 'eps':
        return <FileImageOutlined style={{ ...iconStyle, color: 'var(--app-blueprint-color, #2f54eb)' }} />;
      // 其他未定义的文件类型（使用紫色图标）
      default:
        return <FileUnknownOutlined style={{ ...iconStyle, color: '#722ed1' }} />;
    }
  };

  // 清空搜索
  const handleClearSearch = () => {
    setSearchKeyword('');
    setShowFavoritesOnly(false);
    setDocuments(originalDocuments);
    if (searchInput.current) {
      searchInput.current.focus();
    }
  };

  // 文件类型筛选器和排序器组件
  const renderToolbar = () => {
    // 主要搜索和筛选工具
    const mainTools = (
      <div style={{ display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' }}>
        {/* 选择功能按钮组 - 只在有选中项时显示 */}
        {selectedDocuments.length > 0 && (
          <div style={{ display: 'flex', gap: '4px', flexShrink: 0 }}>
            <Button 
              size="small"
              type="link"
              icon={<PushpinOutlined />}
              onClick={batchPin}
            >
              置顶所选
            </Button>
            <Button 
              size="small"
              type="link"
              icon={<StarOutlined />}
              onClick={batchFavorite}
            >
              收藏所选
            </Button>
            <Button 
              size="small"
              type="link"
              danger
              onClick={batchDelete}
            >
              删除所选
            </Button>
          </div>
        )}
        
        {/* 搜索框和按钮 */}
        <Input
          ref={searchInput}
          placeholder={`搜索${category}文件名`}
          value={searchKeyword}
          onChange={(e) => setSearchKeyword(e.target.value)}
          onPressEnter={() => handleSearch()}
          style={{ width: 200, flexShrink: 1, minWidth: '150px' }}
          suffix={
            <SearchOutlined 
              onClick={() => handleSearch()}
              style={{ cursor: 'pointer' }}
            />
          }
        />
        
        <Button 
          type="text"
          onClick={() => {
            handleSearch();
            if (searchInput.current) {
              searchInput.current.focus();
            }
          }}
          icon={<SearchOutlined />}
        >
          搜索
        </Button>
        
        {searchKeyword && (
          <Button 
            type="text"
            onClick={() => {
              handleClearSearch();
              if (searchInput.current) {
                searchInput.current.focus();
              }
            }}
          >
            清空
          </Button>
        )}
        
        {/* 文件类型筛选器 - 优化为更直观的显示 */}
        <Dropdown
          menu={{
            items: [
              {key: 'all',
                label: '所有类型',
                onClick: () => {
                  setSelectedFileType('all');
                  handleSearch(undefined, 'all');
                }
              },
              {
                key: 'pdf',
                label: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <FilePdfOutlined style={{ marginRight: '8px', color: 'var(--ant-color-danger)' }} />
                    PDF文件
                  </div>
                ),
                onClick: () => {
                  setSelectedFileType('pdf');
                  handleSearch(undefined, 'pdf');
                }
              },
              {
                key: 'word',
                label: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <FileWordOutlined style={{ marginRight: '8px', color: 'var(--ant-color-primary)' }} />
                    Word文件
                  </div>
                ),
                onClick: () => {
                  setSelectedFileType('word');
                  handleSearch(undefined, 'word');
                }
              },
              {
                key: 'excel',
                label: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <FileExcelOutlined style={{ marginRight: '8px', color: 'var(--ant-color-success)' }} />
                    Excel文件
                  </div>
                ),
                onClick: () => {
                  setSelectedFileType('excel');
                  handleSearch(undefined, 'excel');
                }
              },
              {
                key: 'text',
                label: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <FileTextOutlined style={{ marginRight: '8px', color: 'var(--ant-color-text)' }} />
                    文本文件
                  </div>
                ),
                onClick: () => {
                  setSelectedFileType('text');
                  handleSearch(undefined, 'text');
                }
              },
              {
                key: 'image',
                label: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <FileImageOutlined style={{ marginRight: '8px', color: 'var(--ant-color-purple)' }} />
                    图片文件
                  </div>
                ),
                onClick: () => {
                  setSelectedFileType('image');
                  handleSearch(undefined, 'image');
                }
              },
              {key: 'blueprint',
                label: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <FileImageOutlined style={{ marginRight: '8px', color: 'var(--ant-color-info)' }} />
                    蓝图
                  </div>
                ),
                onClick: () => {
                  setSelectedFileType('blueprint');
                  handleSearch(undefined, 'blueprint');
                }
              },
              {
                key: 'other',
                label: (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <FileUnknownOutlined style={{ marginRight: '8px', color: 'var(--ant-color-purple)' }} />
                    其他文件
                  </div>
                ),
                onClick: () => {
                  setSelectedFileType('other');
                  handleSearch(undefined, 'other');
                }
              }
            ]
          }}
        >
          <Button type="text" icon={<FilterOutlined />}>
            {selectedFileType === 'all' ? '文件类型' : (
              selectedFileType === 'pdf' ? 'PDF' :
              selectedFileType === 'word' ? 'Word' :
              selectedFileType === 'excel' ? 'Excel' :
              selectedFileType === 'text' ? '文本' :
              selectedFileType === 'image' ? '图片' :
              selectedFileType === 'blueprint' ? '蓝图' :
                selectedFileType === 'other' ? '其他' : '文件类型'
            )}
          </Button>
        </Dropdown>
      </div>
    );
    
    return mainTools;
  };
  
  // 主渲染内容
  return (
    <Layout className="document-manager-layout" style={{ padding: '24px' }}>
      <Content>
        <div className="document-manager-container">
          <div className="header-section">
            <Title level={4} style={{ marginBottom: '16px' }}>
              {title}
            </Title>
          </div>
          
          {/* 工具栏 - 使用新的响应式布局 */}
          <div style={{ 
            marginBottom: '24px', 
            width: '100%', 
            borderRadius: '8px', 
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.09)',
            padding: '16px',
            backgroundColor: 'var(--ant-color-bg-elevated)'
          }}>
            {/* 全部/收藏标签 - 放置在工具栏最上方，避免在小窗口中被覆盖 */}
            <Tabs 
              activeKey={showFavoritesOnly ? 'favorites' : 'all'} 
              onChange={(key) => {
                const fav = key === 'favorites';
                setShowFavoritesOnly(fav);
                // 直接传入计算出的值，避免 setState 的异步导致的反向筛选
                handleSearch(fav);
              }}
              style={{ 
                marginBottom: '16px',
                width: '150px' // 固定宽度，避免占用太多空间
              }}
              items={[
                { key: 'all', label: '全部' },
                { key: 'favorites', label: '收藏' }
              ]}
            />
            
            {/* 渲染主工具栏 */}
            {renderToolbar()}
            
            {/* 次要工具：排序、全选/取消全选按钮和添加按钮 */}
            <div style={{ display: 'flex', gap: '8px', alignItems: 'center', marginTop: '8px', flexWrap: 'wrap' }}>
              {/* 排序选择器 */}
              <Dropdown
                menu={{
                  items: [
                    {
                      key: 'name',
                      label: (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '120px' }}>
                          按名称排序
                          {sortBy === 'name' && (
                            <>{sortOrder === 'asc' ? <CaretUpOutlined /> : <CaretDownOutlined />}</>
                          )}
                        </div>
                      ),
                      onClick: () => {
                        setSortBy('name');
                        setSortOrder(sortBy === 'name' && sortOrder === 'desc' ? 'asc' : 'desc');
                        handleSearch();
                      }
                    },
                    {
                      key: 'date',
                      label: (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '120px' }}>
                          按日期排序
                          {sortBy === 'date' && (
                            <>{sortOrder === 'asc' ? <CaretUpOutlined /> : <CaretDownOutlined />}</>
                          )}
                        </div>
                      ),
                      onClick: () => {
                        setSortBy('date');
                        setSortOrder(sortBy === 'date' && sortOrder === 'desc' ? 'asc' : 'desc');
                        handleSearch();
                      }
                    },
                    {
                      key: 'size',
                      label: (
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '120px' }}>
                          按大小排序
                          {sortBy === 'size' && (
                            <>{sortOrder === 'asc' ? <CaretUpOutlined /> : <CaretDownOutlined />}</>
                          )}
                        </div>
                      ),
                      onClick: () => {
                        setSortBy('size');
                        setSortOrder(sortBy === 'size' && sortOrder === 'desc' ? 'asc' : 'desc');
                        handleSearch();
                      }
                    }
                  ]
                }}
              >
                <Button type="text" icon={<SortAscendingOutlined />}>
                  {sortBy === 'name' && '名称'}
                  {sortBy === 'date' && '日期'}
                  {sortBy === 'size' && '大小'}
                  {sortOrder === 'asc' ? <CaretUpOutlined style={{ marginLeft: '4px' }} /> : <CaretDownOutlined style={{ marginLeft: '4px' }} />}
                </Button>
              </Dropdown>
              
              {/* 全选/取消全选按钮 */}
              <Button 
                type="text"
                onClick={toggleSelectAll}
              >
                {documents.length > 0 && selectedDocuments.length === documents.length ? '取消全选' : '全选'}
              </Button>
              
              {/* 添加按钮 - 始终在右侧 */}
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={showAddModal}
                style={{ marginLeft: 'auto' }}
              >
                {addButtonText}
              </Button>
            </div>
          </div>
          
          <Card 
            style={{ marginBottom: '24px', width: '100%', borderRadius: '8px', backgroundColor: 'var(--ant-color-bg-elevated)', boxShadow: 'var(--ant-shadow-card)' }}>
          {documents.length > 0 ? (
            <List
              dataSource={documents}
              renderItem={document => (
                <List.Item
                  actions={[
                    <Button
                      key="open"
                      type="link"
                      icon={getFileIcon(document.name)}
                      onClick={() => openDocument(document.name)}
                    >
                      打开
                    </Button>,
                    <Dropdown
                      key="actions"
                      menu={{
                        items: [
                          {
                            key: 'pin',
                            icon: document.isPinned ? <PushpinFilled style={{ color: 'var(--app-primary-color, #1890ff)' }} /> : <PushpinOutlined />,
                            label: document.isPinned ? '取消置顶' : '置顶',
                            onClick: () => togglePin(document.id, document.isPinned || false)
                          },
                          {
                            key: 'favorite',
                            icon: document.isFavorite ? <StarFilled style={{ color: 'var(--app-warning-color, #fadb14)' }} /> : <StarOutlined />,
                            label: document.isFavorite ? '取消收藏' : '收藏',
                            onClick: () => toggleFavorite(document.id, document.isFavorite || false)
                          },
                          {
                            key: 'save',
                            icon: <DownloadOutlined />,
                            label: '保存',
                            onClick: () => saveDocument(document.name)
                          },
                          {
                            key: 'delete',
                            icon: <DeleteOutlined />,
                            label: '删除',
                            danger: true,
                            onClick: () => deleteDocument(document.name)
                          }
                        ]
                      }}
                    >
                      <Button key="more" type="link" icon={<EllipsisOutlined />} />
                    </Dropdown>,
                    <Button
                      key="delete"
                      type="link"
                      danger
                      onClick={() => deleteDocument(document.name)}
                    >
                      删除
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '40px' }}>
                        <input
                          type="checkbox"
                          checked={selectedDocuments.includes(document.id)}
                          onChange={() => toggleSelect(document.id)}
                          style={{ marginRight: '8px' }}
                        />
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          {getFileIcon(document.name)}
                          {document.isPinned && <PushpinFilled style={{ color: 'var(--app-primary-color, #1890ff)', marginLeft: '4px' }} />}
                          {document.isFavorite && <StarFilled style={{ color: 'var(--app-warning-color, #fadb14)', marginLeft: '4px' }} />}
                        </div>
                      </div>
                    }
                    title={document.name}
                    description={`大小: ${document.size} | 修改日期: ${document.date}`}
                  />
                </List.Item>
              )}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '40px', color: 'var(--app-text-secondary, rgba(0,0,0,0.45))' }}>
              {emptyText}
            </div>
          )}
        </Card>
        </div>
      </Content>
      
      {/* 添加文档对话框 */}
      <Modal
        title={addButtonText}
        open={isAddModalVisible}
        onCancel={handleAddModalCancel}
        footer={[
          <Button key="cancel" onClick={handleAddModalCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleAddDocument}>
            添加
          </Button>
        ]}
      >
        <Upload
            name="document-file"
            fileList={fileList}
            onChange={handleUploadChange}
            showUploadList
            multiple
            customRequest={() => {}}
          >
            <Button icon={<PlusOutlined />}>{uploadHint}</Button>
          </Upload>
          <div style={{ marginTop: 16, color: 'var(--app-text-secondary, rgba(0,0,0,0.45))' }}>
            提示：支持批量上传，上传较大的文件时速度较慢
          </div>
      </Modal>
    </Layout>
  );
};

export default DocumentManager;